<template>
	<view class="create-activity">
		<!-- 活动图片上传 -->
		<view class="upload-section">
			<view class="upload-box" @click="chooseImage('event_pic_url')" v-if="!state.event_pic_url">
				<text class="plus">+</text>
				<text class="upload-text">上传图片</text>
			</view>
			<view class="image-preview" v-else>
				<image :src="state.event_pic_url" mode="aspectFill"></image>
				<view class="delete-icon" @click="deleteImage('event_pic_url')">×</view>
			</view>
		</view>

		<!-- 二维码上传 -->
		<view class="upload-section">
			<view class="upload-box" @click="chooseImage('qrcode_url')" v-if="!state.qrcode_url">
				<text class="plus">+</text>
				<text class="upload-text">上传二维码</text>
			</view>
			<view class="image-preview" v-else>
				<image :src="state.qrcode_url" mode="aspectFill"></image>
				<view class="delete-icon" @click="deleteImage('qrcode_url')">×</view>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 活动标题 -->
			<view class="form-item">
				<input type="text" v-model="state.title" placeholder="请填写活动主题" placeholder-class="placeholder-style"
					maxlength="20" />
				<view class="count">{{ state.title.length }}/20</view>
			</view>

			<!-- 活动详情 -->
			<view class="form-item">
				<textarea v-model="state.event_detail" placeholder="请填写服务内容" placeholder-class="placeholder-style"
					maxlength="300" />
				<view class="count">{{ state.event_detail.length }}/300</view>
			</view>

			<!-- 其他表单项 -->
			<view class="form-list">
				<view class="form-item required">
					<text class="label">主办单位</text>
					<input type="text" v-model="state.unit" placeholder="请输入主办单位"
						placeholder-class="placeholder-style" />
				</view>

				<view class="form-item required">
					<text class="label">联系人</text>
					<input type="text" v-model="state.contact_name" placeholder="请输入联系人姓名"
						placeholder-class="placeholder-style" />
				</view>


				<view class="form-item required">
					<text class="label">联系电话</text>
					<input type="number" v-model="state.contact_phone" placeholder="请输入联系电话"
						placeholder-class="placeholder-style" />
				</view>

				<view class="form-item required">
					<text class="label">活动类型</text>
					<picker mode="selector" :range="typeOptions" range-key="name" @change="onTypeChange">
						<view class="picker-value">
							<text :class="{ 'placeholder-style': !state.status }">
								{{ getTypeName(state.status) || '请选择活动类型' }}
							</text>
							<text class="arrow">></text>
						</view>
					</picker>
				</view>

				<view class="form-item required">
					<text class="label">活动地址</text>
					<view class="picker-value">
						<input type="text" v-model="state.event_location" placeholder="请输入活动地址"
							placeholder-class="placeholder-style" />
						<!-- <text :class="{'placeholder-style': !state.event_location}">
							{{state.event_location || '请选择活动地址'}}
						</text>
						<text class="arrow">></text> -->
					</view>
				</view>

				<view class="form-item required">
					<text class="label">活动时间</text>
					<picker mode="multiSelector" :range="dateTimeArray" :value="dateTimeIndex"
						@change="onStartTimeChange" @columnchange="onStartTimeColumnChange">
						<view class="picker-value">
							<text :class="{ 'placeholder-style': !state.start_time }">
								{{ formatDateTime(state.start_time) || '请选择活动时间' }}
							</text>
							<text class="arrow">></text>
						</view>
					</picker>
				</view>

				<view class="form-item required">
					<text class="label">结束时间</text>
					<picker mode="multiSelector" :range="dateTimeArray" :value="dateTimeEndIndex"
						@change="onEndTimeChange" @columnchange="onEndTimeColumnChange">
						<view class="picker-value">
							<text :class="{ 'placeholder-style': !state.end_time }">
								{{ formatDateTime(state.end_time) || '请选择结束时间' }}
							</text>
							<text class="arrow">></text>
						</view>
					</picker>
				</view>

				<view class="form-item required">
					<text class="label">截止报名</text>
					<picker mode="multiSelector" :range="dateTimeArray" :value="dateTimeDeadlineIndex"
						@change="onDeadlineChange" @columnchange="onDeadlineColumnChange">
						<view class="picker-value">
							<text :class="{ 'placeholder-style': !state.event_deadline }">
								{{ formatDateTime(state.event_deadline) || '请选择截止时间' }}
							</text>
							<text class="arrow">></text>
						</view>
					</picker>
				</view>

				<view class="form-item required">
					<text class="label">活动人数</text>
					<input type="number" v-model="state.max_count" placeholder="请输入活动人数"
						placeholder-class="placeholder-style" />
				</view>

				<view class="form-item required">
					<text class="label">活动积分</text>
					<input type="number" v-model="state.jackpoint" placeholder="请输入活动积分"
						placeholder-class="placeholder-style" />
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" @click="submitForm">
			<view v-if="state.submitType == 'add'">发布活动</view>
			<view v-else>修改活动</view>
		</view>
	</view>
	<view class="memberList" v-if="member.list.length > 0">
		<view style="font-weight: 600;margin-bottom: 5px;">参加人员列表</view>
		<view class="listBox">
			<view class="boxItem name"> 姓名 </view>
			<view class="boxItem age"> 年龄 </view>
			<view class="boxItem phone"> 手机号 </view>
			<view class="boxItem delete-btn"> 操作 </view>
		</view>
		<view v-for="item in member.list" @click="getPhone(item.person_phone)" class="listBox">
			<view class="boxItem name"> {{ item.person_name }} </view>
			<view class="boxItem age"> {{ item.age }} </view>
			<view class="boxItem phone"> {{ item.person_phone }} </view>
			<view class="boxItem delete-btn" style="color: red;" @tap="deleteMember(item._id)">
				删除
			</view>
		</view>
		<!-- <view class="memberItem">
				<view class="nameBox">
					{{item.person_name}}
					<view class="tag">{{item.age}}</view>
				</view>
				<view class="phone">
					{{item.person_phone}}
					<img src="/static/phone.png" class="phoneIcon" />
				</view>
			</view> -->

	</view>
	<!-- 活动类型选择弹窗 -->
	<uni-popup ref="typePopup" type="bottom">
		<view class="popup-content">
			<view class="popup-header">
				<text>选择活动状态</text>
				<text class="close" @tap="togglePopup('type', false)">关闭</text>
			</view>
			<view class="popup-list">
				<view class="popup-item" v-for="type in state.activityTypes" :key="type.value" @tap="selectType(type)"
					:class="{ active: state.selectedType === type.label }">
					{{ type.label }}
				</view>
			</view>
		</view>
	</uni-popup>

</template>

<script setup>
import {
	reactive,
	ref,
	onMounted
} from 'vue'
import {
	request
} from '@/js/util.js'
import {
	onLoad
} from "@dcloudio/uni-app";
const member = reactive({
	list: [],
	err: ""
})

const state = reactive({
	id: "", //活动id
	title: '', // 活动标题
	event_pic_url: '', // 活动照片链接
	qrcode_url: '', // 二维码链接
	type: '', // 活动类型
	unit: '', // 主办单位
	contact_name: '', // 联系人名字
	contact_phone: '', // 联系人电话
	start_time: '', // 活动开始时间
	end_time: '', // 活动结束时间
	event_deadline: '', // 报名截止时间
	event_location: '', // 活动地点
	event_detail: '', // 活动明细
	jackpoint: '', // 活动后的积分
	max_count: '', // 最大报名人数
	submitType: "",
})

// 活动类型选项
const typeOptions = [{
	id: 0,
	name: '未开始'
},
{
	id: 1,
	name: '报名进行中'
},
{
	id: 2,
	name: '活动进行中'
},
{
	id: 3,
	name: '已结束'
},
	// ... 其他活动类型
];

// 日期时间选择器数据
const dateTimeArray = ref([])
const dateTimeIndex = ref([0, 0, 0, 0, 0])
const dateTimeEndIndex = ref([0, 0, 0, 0, 0])
const dateTimeDeadlineIndex = ref([0, 0, 0, 0, 0])

// 获取活动详情
const getActivityDetail = async (id) => {
	// 这里添加获取活动详情的接口调用
	let submitData = {
		condition: {
			// status: 1,
			_id: id,
		},
	};
	const result = await request("selectActivity", submitData);
	if (result.status) {
		let data = result.result[0]
		let type = typeOptions.find(x => x.name == data.type)
		state.id = id
		state.title = data.title // 活动标题
		state.event_pic_url = data.event_pic_url // 活动照片链接
		state.qrcode_url = data.qrcode_url // 二维码链接
		state.type = type // 活动类型
		state.unit = data.unit // 主办单位
		state.contact_name = data.contact_name // 联系人名字
		state.contact_phone = data.contact_phone // 联系人电话
		state.start_time = parseInt(data.start_time) // 活动开始时间
		state.end_time = parseInt(data.end_time) // 活动结束时间
		state.event_deadline = parseInt(data.event_deadline) // 报名截止时间
		state.event_location = data.event_location // 活动地点
		state.event_detail = data.event_detail // 活动明细
		state.jackpoint = data.jackpoint // 活动后的积分
		state.max_count = data.max_count // 最大报名人数
		state.status = data.status //活动状态
		console.log('state', state)
		getActivityMember(data._id)
	} else {
		uni.showToast({
			title: "获取失败",
			icon: "error",
		});
	}
};

//获取活动人员
const getActivityMember = async (id) => {
	let submitData = {
		condition: {
			// status: 1,
			examine_status:1,
			activity_id: id,
		},
	};
	const result = await request("selectActivityMember", submitData);
	if (result.status) {
		console.log('result', result)
		member.list = result.result
	} else {
		uni.showToast({
			title: "获取失败",
			icon: "error",
		});
	}
}

const getPhone = (phone) => {
	uni.setClipboardData({
		data: phone
	})
}
// 初始化日期时间选择器数据
onLoad((options) => {
	console.log('options', options)
	let id = options.id
	console.log('id', id)
	if (id) {
		getActivityDetail(id)
	}
	initDateTimeArray()
	state.submitType = id ? 'edit' : 'add'
})

// 初始化日期时间数组
const initDateTimeArray = () => {
	const date = new Date()
	const years = []
	const months = []
	const days = []
	const hours = []
	const minutes = []

	// 生成年份（当前年份开始的5年）
	for (let i = date.getFullYear(); i <= date.getFullYear() + 5; i++) {
		years.push(i + '年')
	}

	// 生成月份
	for (let i = 1; i <= 12; i++) {
		months.push(i < 10 ? '0' + i + '月' : i + '月')
	}

	// 生成天数（先默认31天）
	for (let i = 1; i <= 31; i++) {
		days.push(i < 10 ? '0' + i + '日' : i + '日')
	}

	// 生成小时
	for (let i = 0; i < 24; i++) {
		hours.push(i < 10 ? '0' + i + '时' : i + '时')
	}

	// 生成分钟
	for (let i = 0; i < 60; i++) {
		minutes.push(i < 10 ? '0' + i + '分' : i + '分')
	}

	dateTimeArray.value = [years, months, days, hours, minutes]
}

// 处理时间列变化
const updateDays = (year, month) => {
	const days = dateTimeArray.value[2]
	const temp = new Date(year, month, 0).getDate()

	// 更新天数
	const newDays = []
	for (let i = 1; i <= temp; i++) {
		newDays.push(i < 10 ? '0' + i + '日' : i + '日')
	}
	dateTimeArray.value[2] = newDays
}

// 开始时间列变化处理
const onStartTimeColumnChange = (e) => {
	const column = e.detail.column
	const value = e.detail.value

	if (column === 0 || column === 1) {
		// 年或月变化时，更新天数
		const year = parseInt(dateTimeArray.value[0][dateTimeIndex.value[0]])
		const month = parseInt(dateTimeArray.value[1][dateTimeIndex.value[1]])
		updateDays(year, month)
	}
	dateTimeIndex.value[column] = value
}

// 结束时间列变化处理
const onEndTimeColumnChange = (e) => {
	const column = e.detail.column
	const value = e.detail.value

	if (column === 0 || column === 1) {
		const year = parseInt(dateTimeArray.value[0][dateTimeEndIndex.value[0]])
		const month = parseInt(dateTimeArray.value[1][dateTimeEndIndex.value[1]])
		updateDays(year, month)
	}
	dateTimeEndIndex.value[column] = value
}

// 截止时间列变化处理
const onDeadlineColumnChange = (e) => {
	const column = e.detail.column
	const value = e.detail.value

	if (column === 0 || column === 1) {
		const year = parseInt(dateTimeArray.value[0][dateTimeDeadlineIndex.value[0]])
		const month = parseInt(dateTimeArray.value[1][dateTimeDeadlineIndex.value[1]])
		updateDays(year, month)
	}
	dateTimeDeadlineIndex.value[column] = value
}

// 时间选择确认处理
const onStartTimeChange = (e) => {
	const val = e.detail.value
	const timestamp = getTimestamp(val)
	state.start_time = timestamp
}

const onEndTimeChange = (e) => {
	const val = e.detail.value
	const timestamp = getTimestamp(val)
	state.end_time = timestamp
}

const onDeadlineChange = (e) => {
	const val = e.detail.value
	const timestamp = getTimestamp(val)
	state.event_deadline = timestamp
}

// 将选择器的值转换为时间戳
const getTimestamp = (indexArr) => {
	const year = parseInt(dateTimeArray.value[0][indexArr[0]])
	const month = parseInt(dateTimeArray.value[1][indexArr[1]])
	const day = parseInt(dateTimeArray.value[2][indexArr[2]])
	const hour = parseInt(dateTimeArray.value[3][indexArr[3]])
	const minute = parseInt(dateTimeArray.value[4][indexArr[4]])

	return new Date(year, month - 1, day, hour, minute).getTime()
}

// 格式化时间戳为显示文本
const formatDateTime = (timestamp) => {
	if (!timestamp) return ''
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = (date.getMonth() + 1).toString().padStart(2, '0')
	const day = date.getDate().toString().padStart(2, '0')
	const hour = date.getHours().toString().padStart(2, '0')
	const minute = date.getMinutes().toString().padStart(2, '0')

	return `${year}-${month}-${day} ${hour}:${minute}`
}

// 活动类型选择
const onTypeChange = (e) => {
	const index = e.detail.value;
	state.status = typeOptions[index].id;
};

// 获取活动类型名称
const getTypeName = (typeId) => {
	const type = typeOptions.find(item => item.id === typeId);
	return type ? type.name : '';
};

// 通用上传图片方法
const uploadImage = async (filePath, type) => {
	console.log(111)
	try {
		uni.showLoading({
			title: '上传中...',
			mask: true
		})

	} catch (error) {
		uni.showToast({
			title: '上传失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 选择图片
const chooseImage = (type) => {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			const filePath = res.tempFilePaths[0]
			console.log('filePath', filePath)

			// 获取文件后缀
			const fileType = filePath.substring(filePath.lastIndexOf('.') + 1)

			// 根据时间戳生成对应的文件名
			const fileName = `${Date.now()}.${fileType}`

			const fullPath = `${type == 'qrcode_url' ? 'qrcode' : 'cover'}/${fileName}`
			wx.cloud.uploadFile({
				// 指定上传到的云路径
				cloudPath: fullPath,
				// 指定要上传的文件的小程序临时文件路径
				filePath,
				// 成功回调
				success: res => {
					uni.hideLoading()
					state[type] = res.fileID
				},
				complete: res => {
					member.err = res.errMsg
					uni.showToast({
						title: res.errMsg,
						icon: 'none'
					})
					console.log('res', res)
				}
			})
		}
	})
}


// 删除图片
const deleteImage = (type) => {
	console.log('type', type)
	if (type === 'event_pic_url') {
		state.event_pic_url = ''
	} else if (type === 'qrcode_url') {
		state.qrcode_url = ''
	}
}

// 选择地点
const selectLocation = () => {
	uni.chooseLocation({
		success: (res) => {
			state.event_location = res.address;
		},
		fail: () => {
			uni.showToast({
				title: '选择地址失败',
				icon: 'none'
			});
		}
	})
}

// 表单验证
const validateForm = () => {
	console.log('state', state)
	if (!state.event_pic_url) {
		uni.showToast({
			title: '请上传活动图片',
			icon: 'none'
		})
		return false
	}
	if (!state.qrcode_url) {
		uni.showToast({
			title: '请上传二维码',
			icon: 'none'
		})
		return false
	}
	if (!state.title.trim()) {
		uni.showToast({
			title: '请填写活动主题',
			icon: 'none'
		})
		return false
	}
	if (!state.unit.trim()) {
		uni.showToast({
			title: '请填写主办单位',
			icon: 'none'
		})
		return false
	}
	if (!state.contact_name.trim()) {
		uni.showToast({
			title: '请填写联系人',
			icon: 'none'
		})
		return false
	}
	if (!/^1[3-9]\d{9}$/.test(state.contact_phone)) {
		uni.showToast({
			title: '请填写正确的联系电话',
			icon: 'none'
		})
		return false
	}
	if (!state.event_location) {
		uni.showToast({
			title: '请选择活动地点',
			icon: 'none'
		})
		return false
	}
	if (!state.start_time || !state.end_time || !state.event_deadline) {
		uni.showToast({
			title: '请选择完整的时间',
			icon: 'none'
		})
		return false
	}
	if (state.end_time <= state.start_time) {
		uni.showToast({
			title: '结束时间必须晚于开始时间',
			icon: 'none'
		})
		return false
	}
	if (state.event_deadline >= state.start_time) {
		uni.showToast({
			title: '报名截止时间必须早于活动开始时间',
			icon: 'none'
		})
		return false
	}
	if (!state.max_count || state.max_count <= 0) {
		uni.showToast({
			title: '请填写正确的活动人数',
			icon: 'none'
		})
		return false
	}
	if (!state.jackpoint || state.jackpoint <= 0) {
		uni.showToast({
			title: '请填写正确的活动积分',
			icon: 'none'
		})
		return false
	}
	return true
}

// 提交表单
const submitForm = async () => {


	if (!validateForm()) return

	if (state.submitType == 'add') {
		try {
			const result = await request('addActivity', {
				...state,
				status: 0
			})
			if (result.status) {
				uni.showToast({
					title: '发布成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: result.message || '发布失败',
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: '发布失败',
				icon: 'none'
			})
		}
	} else {
		const result = await request('updateActivity', {
			updateId: state.id,
			updateData: state,
			status: 2
		})
		if (result.status) {
			uni.showToast({
				title: '更新成功',
				icon: 'success'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			uni.showToast({
				title: result.message || '更新失败',
				icon: 'none'
			})
		}

	}
}

const deleteMember = async (id) => {
	console.log('id', id)
	let submitData = {
		delete_id: id
	}
	const result = await request('deleteActivityUser', submitData)
	console.log('deleteMember:', submitData, result)
	if (result.status) {
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		})
		getActivityMember(state.id)
	} else {
		uni.showToast({
			title: result.message || '删除失败',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss">
.create-activity {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx 20rpx 150rpx 20rpx;

	.upload-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		// 添加标题
		.section-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;

			&::before {
				content: '*';
				color: #ff5555;
				margin-right: 4rpx;
			}
		}

		.upload-box {
			width: 200rpx;
			height: 200rpx;
			background: #f8f8f8;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			border: 2rpx dashed #ddd;
			border-radius: 12rpx;

			.plus {
				font-size: 60rpx;
				color: #999;
				margin-bottom: 10rpx;
			}

			.upload-text {
				font-size: 24rpx;
				color: #999;
			}
		}

		.image-preview {
			position: relative;
			width: 200rpx;
			height: 200rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 12rpx;
			}

			.delete-icon {
				position: absolute;
				right: -20rpx;
				top: -20rpx;
				width: 40rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				background: rgba(0, 0, 0, 0.5);
				color: #fff;
				border-radius: 50%;
			}
		}
	}

	.form-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.form-item {
			display: flex;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eee;

			&:last-child {
				border-bottom: none;
			}

			.label {
				width: 160rpx;
				font-size: 28rpx;
				color: #333;
				flex-shrink: 0;

				&::before {
					content: '*';
					color: #ff5555;
					margin-right: 4rpx;
				}
			}

			input {
				flex: 1;
				font-size: 28rpx;
			}

			.picker-value {
				flex: 1;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 28rpx;

				.arrow {
					color: #999;
					margin-left: 10rpx;
				}
			}
		}

		// 活动标题和详情的特殊样式
		.form-item:first-child,
		.form-item:nth-child(0) {
			display: block;

			input,
			textarea {
				width: 100%;
				margin-top: 20rpx;
			}

			.count {
				text-align: end;
				color: #999;
			}
		}
	}

	.submit-btn {
		position: fixed;
		z-index: 100;
		left: 40rpx;
		right: 40rpx;
		bottom: 40rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: #ff5555;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
	}
}

.placeholder-style {
	color: #999;
}

.memberList {
	background-color: #fff;
	border-radius: 4px;
	margin: 5px;
	padding: 10px 10px 120px 10px;
	margin-top: 20px;
	margin-bottom: 100px;

	.listBox {
		border: 2px solid #333;
		display: flex;
		align-items: center;

		.boxItem {
			border-right: 2px solid #333;
			// border-left: 2px solid #333;
			padding: 4px 2px;
		}

		.name {
			width: 18%;
		}

		.age {
			width: 10%;
		}

		.phone {
			flex: 1;
		}

		.delete-btn {
			width: 100rpx;
			// color: #ff5555;
		}
	}

	.memberItem {
		padding: 12px;
		border-radius: 8px;
		background-color: #f0f0f0;
		color: #333;
		margin: 10px 0;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.nameBox {
			display: flex;
			align-items: flex-start;
		}

		.tag {
			color: #fff;
			background-color: #1890ff;
			border-radius: 4px;
			padding: 2px 6px;
			margin-left: 8px;
			font-size: 9px;
		}

		.phone {
			color: #389e0d;

			.phoneIcon {
				width: 30rpx;
				height: 30rpx;
				margin-left: 5px;
			}
		}
	}
}
</style>